﻿create PROCEDURE Sync.SP_LoanCancellingDebts_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @LoanCancellingDebts_Temp TABLE 
		(
			LoanCancellingDebtID UniqueIdentifier,
			[LoanID] uniqueidentifier,
				[Notes] nvarchar(MAX),
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @LoanCancellingDebts_Temp 
	   SELECT	Tbl.Col.value('LoanCancellingDebtID[1]','uniqueidentifier') LoanCancellingDebtID,
                Tbl.Col.value('LoanID[1]', 'uniqueidentifier') [LoanID],
Tbl.Col.value('Notes[1]', 'nvarchar(MAX)') [Notes],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/LoanCancellingDebts') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[LoanCancellingDebts] ([LoanCancellingDebtID],[LoanID],[Notes])
	SELECT t.[LoanCancellingDebtID],t.[LoanID],t.[Notes]
	FROM  @LoanCancellingDebts_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.LoanCancellingDebts_Tracking s
        WHERE t.LoanCancellingDebtID = s.LoanCancellingDebtID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[LoanCancellingDebts]
	SET [LoanCancellingDebts].[LoanID] = t.[LoanID],[LoanCancellingDebts].[Notes] = t.[Notes] 
	FROM [dbo].[LoanCancellingDebts] s JOIN @LoanCancellingDebts_Temp t 
    ON t.LoanCancellingDebtID = s.LoanCancellingDebtID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.LoanCancellingDebts_Tracking r
				  WHERE t.LoanCancellingDebtID = r.LoanCancellingDebtID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[LoanCancellingDebts]
    FROM @LoanCancellingDebts_Temp t JOIN [dbo].[LoanCancellingDebts] s
    ON t.LoanCancellingDebtID = s.LoanCancellingDebtID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END











